package person.wend.javalearnexample.util.concurrent.executor;

import java.util.concurrent.*;

public class ExecutorCompletionServiceExample {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 创建一个固定大小为2的线程池
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 创建一个 ExecutorCompletionService 实例
        ExecutorCompletionService<Integer> ecs = new ExecutorCompletionService<>(executor);

        // 提交一些任务给 ECS
        for (int i = 0; i < 5; i++) {
            final int taskNumber = i;
            ecs.submit(() -> {
                System.out.println("Executing Task " + taskNumber);
                Thread.sleep((long) (Math.random() * 1000)); // 模拟不同耗时的操作
                return taskNumber * 2;
            });
        }

        // 获取并处理任务的结果，按照任务完成的顺序
        for (int i = 0; i < 5; i++) {
            Future<Integer> future = ecs.take(); // 阻塞直到有任务完成
            Integer result = future.get(); // 获取任务的结果
            System.out.println("Task completed with result: " + result);
        }

        // 关闭线程池
        executor.shutdown();
        if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
            executor.shutdownNow();
        }
    }
}